# coding=utf-8
import logging
import random
import base64
import rsa


class RsaCrypter(object):
    """
    RSA加密
    """

    def __init__(self, modulus, exponent):
        self.modulus = modulus
        self.exponent = exponent

    def update_aes_encrypt(self):
        aes_key = self.random_str(32)
        aes_iv = self.random_str(16)
        aes_token = aes_key + '|' + aes_iv

        modulus = int(self.modulus, 16)
        exponent = int(self.exponent, 16)

        rsa_pubkey = rsa.PublicKey(modulus, exponent)
        crypto = rsa.encrypt(aes_token.encode(), rsa_pubkey)
        b64str = base64.b64encode(crypto)
        logging.info('UpdateEncrypt Key：%s' % b64str)

        logging.info('==============================')
        logging.info('AES Key：%s' % aes_key)
        logging.info('AES IV：%s' % aes_iv)
        logging.info('AES Token：%s' % aes_token)
        logging.info('RSA Modulus：%s' % self.modulus)
        logging.info('RSA Exponent：%s' % self.exponent)
        logging.info('RSA Key：%s' % b64str)
        logging.info('==============================')

        return {
            'rsa_modulus': self.modulus,
            'rsa_exponent': self.exponent,
            'rsa_key': b64str,
            'aes_key': aes_key,
            'aes_iv': aes_iv,
            'aes_token': aes_token,
        }

    def random_str(self, len=32):
        """
        生成随机字符串
        :param len: 长度
        :return:
        """
        return ''.join(
            random.sample([
                'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f',
                'e', 'd', 'c', 'b', 'a', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K',
                'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
            ], len)
        )


if __name__ == '__main__':
    rs = RsaCrypter(
        'A6BBBB10B1A85ED9BE1CE3FC8AAB1A13AD1BE2BD2037AFB993127C63691E903FA269B6FCDDEC915C76024396C9C47853B6863433FF7540D9575540F06182D7D109F7D8BDD7FFE46050E2C34B63C632484367C92A8BE67760344D9371484736EB5B3B80FD7315A897ED3F84460DA7690853B444D7D12C27B6148D91FAFF622E83',
        '010001'
    )
    s = rs.update_aes_encrypt()
    print(s)
